package org.fuys.etp.repo.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.fuys.etp.core.model.vo.TpConfigVO;
import org.fuys.etp.core.model.vo.TpRegulationStrategyVO;
import org.fuys.etp.repo.converter.PoToVoConverter;
import org.fuys.etp.repo.converter.VoToPoConverter;
import org.fuys.etp.repo.mapper.EtpStrategyMapper;
import org.fuys.etp.repo.po.EtpStrategy;
import org.fuys.etp.repo.repository.IEtpStrategyRepository;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @projectName: fuys-etp
 * @package: org.fuys.etp.repo.repository.impl
 * @className: EtpStrategyRepository
 * @author: WangJing
 * @description: 弹性线程池策略仓库实现类
 * @date: 2025/2/6 23:38
 * @version: 1.0
 */
@Component
public class EtpStrategyRepository implements IEtpStrategyRepository {

    @Resource
    private EtpStrategyMapper etpStrategyMapper;

    @Resource
    private EtpConfigRepository configRepository;

    @Override
    public boolean insertStrategy(TpRegulationStrategyVO strategy) {
        final EtpStrategy converter = VoToPoConverter.converter(strategy);
        etpStrategyMapper.insert(converter);
        return true;
    }

    @Override
    public boolean updateStrategy(Integer strategyId, TpRegulationStrategyVO strategy) {
        final EtpStrategy converter = VoToPoConverter.converter(strategy);
        etpStrategyMapper.update(converter,new LambdaUpdateWrapper<EtpStrategy>()
                .eq(EtpStrategy::getStrategyId,strategyId));
        return true;
    }

    @Override
    public boolean deleteStrategy(Integer strategyId) {
        etpStrategyMapper.delete(new LambdaQueryWrapper<EtpStrategy>()
                .eq(EtpStrategy::getStrategyId, strategyId));
        return true;
    }

    @Override
    public TpRegulationStrategyVO getStrategyById(String strategyId) {
        final EtpStrategy etpStrategy = etpStrategyMapper.selectOne(new LambdaQueryWrapper<EtpStrategy>()
                .eq(EtpStrategy::getStrategyId, strategyId));
        if(etpStrategy == null || etpStrategy.getLoadChain() == null){
            return null;
        }
        final List<Integer> collect = Arrays.stream(etpStrategy.getLoadChain().split(",")).map(Integer::valueOf)
                .collect(Collectors.toList());
        final List<TpConfigVO> tpConfigVOS = configRepository.
                selectConfigByIds(etpStrategy.getStrategyType().toString(), collect);
        return PoToVoConverter.convert(etpStrategy,tpConfigVOS);
    }
}
